package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.VoiceVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.PeachblossomApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class PeachblossomService {

    @Reference
    private PeachblossomApi peachblossomApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private final String VIDEO_COUNT = "VIDEO_COUNT_";

    //发送语音消息
    public ResponseEntity<Object> sendVoice(MultipartFile soundFile) throws IOException {
        String fileName = soundFile.getOriginalFilename();//获取文件名
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);//获取后缀名
        StorePath storePath = storageClient.uploadFile(
                soundFile.getInputStream(), soundFile.getSize(), suffix, null);//保存语音到fastdfs
        String videoUrl = fdfsWebServer.getWebServerUrl()+storePath.getFullPath();//记录地址
        Long id = UserHolder.getUserId();
        UserInfo userInfo = userInfoApi.findById(id);//获取用户信息
        Voice voice = new Voice();
        voice.setGender(userInfo.getGender());
        voice.setAge(userInfo.getAge());
        voice.setSoundUrl(videoUrl);
        voice.setCreated(System.currentTimeMillis());
        voice.setState(0);
        voice.setUserId(id);

        peachblossomApi.saveVoice(voice);//保存到MongoDB去
        return ResponseEntity.ok(null);
    }

    //桃花传音-接收语音
    public ResponseEntity<Object> getVoice() {
        //在用户每天接收时，在redis上创建一个记录，在每天凌晨清空
        Long id = UserHolder.getUserId();
        String count = redisTemplate.opsForValue().get(VIDEO_COUNT + id);
        //根据当前时间，返回和明天0点(可调整)相差的毫秒值
        Long timeout = timeOut();
        String format = new SimpleDateFormat("HH小时mm分ss秒").format(new Date(timeout));
        if (count==null){
            //如果查不到，第一次查询，保存数据，并且设置过期时间为凌晨00:00
            count = "10" ;
            redisTemplate.opsForValue().set(VIDEO_COUNT + id,count,timeout, TimeUnit.MILLISECONDS);
        }
        Integer countInt = Integer.parseInt(count);
        //如果为0
        if (countInt==0){
            return ResponseEntity.status(500).body(ErrorResult.countError(format));
        }

        //从MongoDB中获取最近一周的语音消息列表，并从中随机挑选一条(并且不包含自己的)，莫得推荐系统
        List<Voice> voiceList = peachblossomApi.find(id);
        //如果没有语音信息则返回空
        if (CollectionUtils.isEmpty(voiceList)){ return ResponseEntity.status(500).body(ErrorResult.noMoreError()); }
        VoiceVo voiceVo = new VoiceVo();
        //修改剩余的获取次数，并将值重新返回到redis中
        countInt -= 1;
        redisTemplate.opsForValue().set(VIDEO_COUNT + id,countInt.toString(),timeout, TimeUnit.MILLISECONDS);
        voiceVo.setRemainingTimes(countInt);
        //根据集合长度获取一个随机数
        int randomNum = new Random().nextInt(voiceList.size());
        //根据这个随机数获取对应下标的voice
        Voice voice = voiceList.get(randomNum);
        //获取ID，根据ID获取userinfo，封装到vo中
        UserInfo userInfo = userInfoApi.findById(voice.getUserId());
        voiceVo.setId(userInfo.getId().intValue());
        BeanUtils.copyProperties(userInfo,voiceVo);
        //将该voice状态改为1
        voice.setState(1);
        //更新到MongoDB中
        peachblossomApi.update(voice);
        //获取链接
        voiceVo.setSoundUrl(voice.getSoundUrl());
        return ResponseEntity.ok(voiceVo);
    }

    private Long timeOut() {
        LocalDateTime today = LocalDateTime.now();
        LocalDateTime tomorrow = LocalDateTime.now().plusDays(1L).withHour(0).withMinute(0).withSecond(0);
        //测试改成一分钟之后
        //LocalDateTime tomorrow = LocalDateTime.now().plusMinutes(1);
        return ChronoUnit.MILLIS.between(today, tomorrow);
    }
}
